package com.mixsmart.web.tag;

import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import com.mixsmart.enums.YesNoType;
import com.mixsmart.utils.StringUtils;

/**
 * 表格异步树
 * @author lmq <br />
 * 2016年8月2日
 * @version 1.0
 * @since JDK1.6
 */
public class TableAsyncTreeTag extends TableTreeTag {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5412228218160950424L;
	
	/**
	 * 异步加载请求地址
	 */
	private String asyncUrl;

	@Override
	public int doStartTag() throws JspException {
		try {
			JspWriter out = this.pageContext.getOut();
			this.page = null;
			thWidth = printTableHeader(out,"cnoj-async-tree-table",null,true,null);
			if(null != thWidth) {
				this.printTableBody(out);
				printFooter(out);
			}
			if(!StringUtils.isEmpty(stylesClass)) {
				tdStyles = stylesClass.split(",");
			}
		} catch (Exception e) {
			throw new JspException(e.getMessage());
		}
		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}

	@Override
	public void release() {
		super.release();
	}

	@Override
	protected void printTableBody(JspWriter out) {
		try {
			out.println("<tbody>");
    		if(!OP_SUCCESS.equals(mixResp.getResult())) {
    			int cols = headers.split(",").length;
    			out.println("<tr><td colspan='"+cols+"' class='text-center'>"+mixResp.getMsg()+"</td></tr>");
    		} else {
    			List<Object> objs = mixResp.getDatas();
    			for (Object obj : objs) {
					Object[] objArray = (Object[]) obj;
					if(isParent(objArray)) {
						out.println(getParentHtml(objArray, countLayer(StringUtils.handNull(objArray[1]), objs)));
					} else {
						out.println(getHtml(objArray, countLayer(StringUtils.handNull(objArray[1]), objs)));
					}
				}
    		}
    		out.println("</tbody></table></div>");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 判断是否为父层
	 * @param objs　数组
	 * @return　如果为父层，返回：true；否则返回：false
	 */
	protected boolean isParent(Object[] objs) {
		boolean is = true;
		if(objs[objs.length-1].toString().equals(YesNoType.NO.getValue())){
			is = false;
		}
		return is;
	}
	
	/**
	 * 生成父级HTML代码 
	 * @param objArray　数组
	 * @param layer　层级
	 * @return 返回生成的HTML代码
	 */
	protected String getParentHtml(Object[] objArray,int layer) {
		StringBuffer strBuff = new StringBuffer();
		String classOpTree = "tr-shrink-tree";
		String cols1Value = null;
		int startIndex = 0;
		if(isId==1 && isIdShow==1) {
			cols1Value = StringUtils.handNull(objArray[3]);
			startIndex = 4;
		} else if (isId==1 && isIdShow==0) {
			cols1Value = StringUtils.handNull(objArray[4]);
			startIndex = 5;
		} else {
			cols1Value = StringUtils.handNull(objArray[3]);
			startIndex = 4;
		}
		int colNum = objArray.length - startIndex; 
		if(StringUtils.isNotEmpty(this.asyncUrl) && this.asyncUrl.indexOf("?") == -1) {
			this.asyncUrl += "?1=1";
		}
		strBuff.append("<tr data-col-num='"+colNum+"' data-layer='"+layer+"'  data-async-url='"+this.asyncUrl+"?parentId="+StringUtils.handNull(objArray[0])+"' id='t-"+StringUtils.handNull(objArray[0])+"' class='tr-tree tr-async-tree "+classOpTree+" t-tree-layer"+layer+" t-"+StringUtils.handNull(objArray[1])+"' parentid='t-"+StringUtils.handNull(objArray[1])+"'>");
		int count = 0;
		String tdStyle = "";
		if(null != tdStyles) {
			if(count>=tdStyles.length) {
				tdStyle = tdStyles[tdStyles.length-1];
			} else {
				tdStyle = tdStyles[count];
			}
		}
		String tdOpData = "shrink-data";
		//String uiIconOpData = "fa-caret-right";
		String uiIconOpData = "ui-icon-triangle-1-e";
		
		String a = null;
		if(null != alinks && alinks.size()>0) {
			for (ALink alink : alinks) {
				int postion = Integer.parseInt(alink.getLinkPostion());
				if(0 == postion) {
					a = getALinkContent(alink, objArray);
					a = "<a "+a+">"+cols1Value+"</a>";
					break;
				}
			}
		}
		if(StringUtils.isEmpty(a)) {
			a = cols1Value;
		}
		
		strBuff.append("<td class='op-tree "+tdOpData+" td-tree "+(StringUtils.isEmpty(tdStyle)?"":tdStyle)+
				"' style='width:"+thWidth[count]+"'><span class='ui-icon "+uiIconOpData+" left'></span> &nbsp;"+a+"</td>");
		for (int i = startIndex; i < objArray.length-1; i++) {
			count++;
			if(null != tdStyles) {
				if(count>=tdStyles.length) {
					tdStyle = tdStyles[tdStyles.length-1];
				} else {
					tdStyle = tdStyles[count];
				}
			}
			String thWithStyle = "";
			if(!StringUtils.isEmpty(thWidth[count])) {
				thWithStyle = "style='width:"+thWidth[count]+"'";
			}
			a = null;
			if(null != alinks && alinks.size()>0) {
				for (ALink alink : alinks) {
					int postion = Integer.parseInt(alink.getLinkPostion());
					if(count == postion) {
						a = getALinkContent(alink, objArray);
						a = "<a "+a+">"+StringUtils.handNull(objArray[i])+"</a>";
						break;
					}
				}
			}
			if(StringUtils.isEmpty(a)) {
				a = StringUtils.handNull(objArray[i]);
			}
			strBuff.append("<td "+(StringUtils.isEmpty(tdStyle)?"":"class='"+tdStyle+"'")+" "+thWithStyle+">"+a+"</td>");
			
		}
		strBuff.append("</tr>");
		return strBuff.toString();
	}
	
	/**
	 * 生成HTML代码 
	 * @param objArray 内容数组
	 * @param layer　层级
	 * @return　返回生成HTML代码 
	 */
	protected String getHtml(Object[] objArray,int layer) {
		StringBuffer strBuff = new StringBuffer();
		strBuff.append("<tr id='t-"+StringUtils.handNull(objArray[0])+"' class='tr-tree tr-shrink-tree t-tree-layer"+layer+" t-"+StringUtils.handNull(objArray[1])+"' parentid='t-"+StringUtils.handNull(objArray[1])+"'>");
		String cols1Value = null;
		int startIndex = 0;
		if(isId==1 && isIdShow==1) {
			cols1Value = StringUtils.handNull(objArray[3]);
			startIndex = 4;
		} else if (isId==1 && isIdShow==0) {
			cols1Value = StringUtils.handNull(objArray[4]);
			startIndex = 5;
		} else {
			cols1Value = StringUtils.handNull(objArray[3]);
			startIndex = 4;
		}
		
		String a = null;
		if(null != alinks && alinks.size()>0) {
			for (ALink alink : alinks) {
				int postion = Integer.parseInt(alink.getLinkPostion());
				if(0 == postion) {
					a = getALinkContent(alink, objArray);
					a = "<a "+a+">"+cols1Value+"</a>";
					break;
				}
			}
		}
		if(StringUtils.isEmpty(a)) {
			a = cols1Value;
		}
		int count = 0;
		String tdStyle = "";
		if(null != tdStyles) {
			if(count>=tdStyles.length) {
				tdStyle = tdStyles[tdStyles.length-1];
			} else {
				tdStyle = tdStyles[count];
			}
		}
		strBuff.append("<td class='td-tree "+(StringUtils.isEmpty(tdStyle)?"":tdStyle)+"' style='width:"+thWidth[count]+"'><span class='ui-icon ui-icon-radio-on left'></span> &nbsp;&nbsp;"+a+"</td>");
		for (int i = startIndex; i < objArray.length-1; i++) {
			count++;
			if(null != tdStyles) {
				if(count>=tdStyles.length) {
					tdStyle = tdStyles[tdStyles.length-1];
				} else {
					tdStyle = tdStyles[count];
				}
			}
			String thWithStyle = "";
			if(!StringUtils.isEmpty(thWidth[count])) {
				thWithStyle = "style='width:"+thWidth[count]+"'";
			}
			a = null;
			if(null != alinks && alinks.size()>0) {
				for (ALink alink : alinks) {
					int postion = Integer.parseInt(alink.getLinkPostion());
					if(count == postion) {
						a = getALinkContent(alink, objArray);
						a = "<a "+a+">"+StringUtils.handNull(objArray[i])+"</a>";
						break;
					}
				}
			}
			if(StringUtils.isEmpty(a)) {
				a = StringUtils.handNull(objArray[i]);
			}
			strBuff.append("<td "+(StringUtils.isEmpty(tdStyle)?"":"class='"+tdStyle+"'")+" "+thWithStyle+">"+a+"</td>");
		}
		strBuff.append("</tr>");
		return strBuff.toString();
	}

	public String getAsyncUrl() {
		return asyncUrl;
	}

	public void setAsyncUrl(String asyncUrl) {
		this.asyncUrl = asyncUrl;
	}
	
}
